package com.dong.zk;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author: dzj
 * @date 2018/10/10-9:54
 */
public class ZkConnectSessionWatcher implements Watcher {
    public static final String zkServerPath = "10.0.109.142:2181";
    public static final Integer timeout=5000;
    public static Logger logger = LoggerFactory.getLogger(ZkConnectSessionWatcher.class);

    public static void main(String[] args) throws IOException, InterruptedException {
        ZooKeeper zk = new ZooKeeper(zkServerPath, timeout, new ZkConnectSessionWatcher());
        long sessionId = zk.getSessionId();
        byte[] sessionPasswd = zk.getSessionPasswd();

        logger.warn("客户端开始连接zookeeper服务器...");
        logger.warn("连接状态: {}",zk.getState());
         Thread.sleep(2000);

        logger.warn("连接状态: {}",zk.getState());
        Thread.sleep(5000);
        logger.warn("开始重新连接....");
        zk = new ZooKeeper(zkServerPath, timeout, new ZkConnectSessionWatcher(),sessionId,sessionPasswd);

        logger.warn("客户端重新连接zookeeper服务器...");
        logger.warn("重新连接状态: {}",zk.getState());
         Thread.sleep(2000);
        logger.warn("重新连接状态: {}",zk.getState());
         new Thread().sleep(5000);


    }
    public void process(WatchedEvent watchedEvent) {
        logger.warn("接受到事件通知: "+watchedEvent);
    }
}
